<template>
  <div class="newinfo-wraper">
    <el-form
      ref="drawerForm"
      :model="drawerForm"
      :rules="drawerRules"
      label-width="140px"
      size="mini"
      @submit.native.prevent
    >
      <el-form-item label="工作量指标编码：" prop="workloadCode">
        <el-input
          v-model.trim="drawerForm.workloadCode"
          style="width:400px"
          placeholder="请输入"
          clearable
          :disabled="current&&current.id ? true : false"
        />
      </el-form-item>
      <el-form-item label="工作量指标名称：" prop="workloadName">
        <el-input
          v-model.trim="drawerForm.workloadName"
          style="width:400px"
          placeholder="请输入"
          clearable
          :disabled="current&&current.id ? true : false"
        />
      </el-form-item>
      <el-form-item label="核算单元名称：" prop="dept">
        <el-select
          :key="keyMath"
          v-model="drawerForm.dept"
          placeholder="请选择"
          multiple
          clearable
          style="width:400px"
          @change="deptChange"
        >
          <el-option
            v-for="item in dptList"
            :key="item.code"
            :label="item.nameAndCode"
            :value="item.code"
          />
        </el-select>
        <el-checkbox v-model="checked" size="small" @change="deptChangeChecked">全选</el-checkbox>
      </el-form-item>
      <el-form-item label="开单科室名称：" prop="billing">
        <el-select
          v-model="drawerForm.billing"
          placeholder="请选择"
          filterable
          multiple
          clearable
          style="width:400px"
        >
          <el-option
            v-for="item in kzdptList"
            :key="item.code"
            :label="item.nameAndCode"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="执行科室名称：" prop="execute">
        <el-select
          v-model="drawerForm.execute"
          placeholder="请选择"
          filterable
          multiple
          clearable
          style="width:400px"
        >
          <el-option
            v-for="item in kzdptList"
            :key="item.code"
            :label="item.nameAndCode"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设置：" required>
        <div class="top-box">
          <div class="left-box card-box">
            <div class="undline">选择统计项目</div>
            <div class="search-box" style="flex-direction: column">
              <FilterForm
                ref="gxForm"
                :elements="hospitalElement"
                @submit="handleHospitalSearch"
              />
            </div>
            <div class="table-box">
              <Table
                :selection="true"
                :columns="tableLColumns"
                :loading="tableLLoading"
                :data="tableLData"
                :pagination="{
                  total: totalL,
                  current: currentL,
                  pageSize: pageLSize,
                }"
                @paginationChange="pageChange"
                @rowSelection="handleSelection"
              />
            </div>
          </div>
          <div class="middle-box">
            <Button
              icon="icon-a-ziyuan3"
              :btn-loading="btnLoading"
              @click="handleBtnConfirm"
            >确定</Button>
          </div>
          <div class="right-box card-box">
            <div class="undline">已选统计项目</div>
            <div class="search-box" style="flex-direction: column">
              <FilterForm
                ref="filterForm"
                :elements="SystermElement"
                noimmediate
                @submit="handleSystermSearch"
              />
            </div>
            <div class="table-box systerm-box">
              <Table
                ref="systermRef"
                :columns="tableRColumns"
                :loading="tableRLoading"
                :data="tableRData"
                :hide-pagination="true"
              >

                <template #count="{ row }">
                  <el-input v-model="row.count" size="mini" placeholder="请输入" />
                </template>
                <template #unit="{ row }">
                  <el-select v-model="row.unit" size="mini" placeholder="请选择">
                    <el-option
                      v-for="item in unitList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </template>

                <template #caozuo="{ row }">
                  <Tooltip content="删除" icon="delete" @click="handleDelete(row)" />
                </template>
              </Table>
            </div>
          </div>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
let tableSourceList = []
import {
  sysAccountingUnitPull,
  listByCodeOrName,
  listProjectTargetAdministrationPull,
  updateWorkloadTargetAdministrationInfo,
  HISDeptCode
} from '@/api/targetManagement'
export default {
  props: {
    current: Object
  },
  data() {
    return {
      keyMath: '',
      unitList: [],
      totalL: 0,
      currentL: 1,
      pageLSize: 20,
      dptList: [],
      kzdptList: [],
      btnLoading: false,
      totalR: 0,
      currentR: 1,
      pageRSize: 100,
      tableRData: [],
      tableRLoading: false,
      tableRColumns: [
        {
          title: '统计项目编码',
          dataIndex: 'projectCode'
        },
        {
          title: '统计项目名称',
          dataIndex: 'projectName'
        },
        {
          title: '点数',
          dataIndex: 'count',
          type: 'otherTag',
          width: 90
        },
        {
          title: '单位',
          dataIndex: 'unit',
          type: 'otherTag',
          width: 110
        },
        {
          title: '操作',
          dataIndex: 'caozuo',
          type: 'otherTag',
          width: 50
        }
      ],
      SystermElement: [
        {
          label: '',
          type: 'input',
          key: 'nameOrNumber',
          value: '',
          width: '240',
          placeholder: '请输入统计项目编码/统计项目名称'
        }
      ],
      tableLData: [],
      tableLLoading: false,
      tableLColumns: [
        {
          title: '统计项目编码',
          dataIndex: 'projectCode'
        },
        {
          title: '统计项目名称',
          dataIndex: 'projectName'
        }
      ],
      hospitalElement: [
        {
          label: '',
          type: 'input',
          key: 'nameOrNumber',
          value: '',
          width: '240',
          placeholder: '请输入统计项目编码/统计项目名称'
        }
      ],
      leftSelections: [],
      rightSelections: [],
      drawerForm: {
        workloadCode: '',
        workloadName: '',
        dept: [],
        billing: [],
        execute: []
      },
      drawerRules: {
        workloadCode: [
          { required: true, message: '请输入工作量指标编码', trigger: 'blur' }
        ],
        workloadName: [
          { required: true, message: '请输入工作量指标名称', trigger: 'blur' }
        ],
        dept: [
          { required: false, message: '请选择核算单元名称', trigger: 'change' }
        ],
        billing: [
          { required: false, message: '请选择开单科室名称', trigger: 'change' }
        ],
        execute: [
          { required: false, message: '请选择执行科室名称', trigger: 'change' }
        ]
      },
      checked: false
    }
  },
  created() {
    tableSourceList = []
    this.getSelect()
    if (this.current && this.current.id) {
      this.getDetails()
    }
  },
  methods: {
    deptChangeChecked() {
      this.drawerForm.dept = []
      if (this.checked) {
        this.drawerForm.dept = this.dptList.map(item => item.code)
        // this.drawerForm.dept = this.kzdptList.map(item => item.code)
      }
      this.keyMath = Math.random()
    },
    deptChange(val) {
      if (val.length !== this.dptList.length) {
        this.checked = false
      } else {
        this.checked = true
      }
    },
    getDetails() {
      updateWorkloadTargetAdministrationInfo({
        period: this.current.period,
        id: this.current.id

      }).then(res => {
        if (res.code === 200) {
          const { workloadCode, workloadName, projectWork, workDeptInfo, exeDeptWork, billDeptWork } = res.data
          this.drawerForm.workloadCode = workloadCode
          this.drawerForm.workloadName = workloadName
          this.drawerForm.dept = workDeptInfo
          this.drawerForm.billing = billDeptWork
          this.drawerForm.execute = exeDeptWork
          tableSourceList = projectWork
          this.tableRData = projectWork
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    getFormData() {
      let flag = false
      let formData = {}
      this.$refs['drawerForm'].validate((valid) => {
        if (valid) {
          if (/[\u4e00-\u9fa5]+/.test(this.drawerForm.workloadCode)) {
            this.$message.warning('工作量指标编码不能包含中文')
            return
          }
          try {
            for (let i = 0; i < this.tableRData.length; i++) {
              const item = this.tableRData[i]
              if (item.count === '' || item.count === undefined || item.count === null) { // 点数
                throw new Error(`统计项目编码${item.projectCode}的点数不能为空`)
              } else {
                if (!/^([0-9]*)(\.\d{1,4})?$/.test(item.count)) {
                  throw new Error(`统计项目编码${item.projectCode}点数的小数位最多四位`)
                }
              }
              if (!item.unit) { // 单位
                throw new Error(`请选择统计项目编码${item.projectCode}的单位`)
              }
            }
          } catch (error) {
            this.$message.warning(error.message)
            return
          }
          flag = true
          formData = {
            workloadCode: this.drawerForm.workloadCode,
            workloadName: this.drawerForm.workloadName,
            dept: this.drawerForm.dept?.map(item => {
              return {
                deptCode: item,
                deptName: this.dptList.find(it => it.code === item)?.name
              }
            }),
            billDept: this.drawerForm.billing?.map(item => {
              return {
                billDeptCode: item,
                billDeptName: this.kzdptList.find(it => it.code === item)?.name
              }
            }),
            exeDept: this.drawerForm.execute?.map(item => {
              return {
                exeDeptCode: item,
                exeDeptName: this.kzdptList.find(it => it.code === item)?.name
              }
            }),
            project: this.tableRData?.map(item => {
              item.targetAdministrationCode = item.projectCode
              return item
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
      return {
        flag,
        formData
      }
    },
    handleBtnConfirm() { // 确定
      if (this.leftSelections.length === 0) {
        this.$message.warning('请选择统计项目数据')
        return
      }
      if (tableSourceList.length > 0) {
        this.leftSelections.forEach(item => {
          if (tableSourceList.findIndex(element => element.id === item.id) === -1) {
            tableSourceList.push(item)
          }
        })
      } else {
        tableSourceList = this.leftSelections
      }
      this.tableRData = tableSourceList
    },
    getRightTable() {
      const regex = new RegExp(this.newRCondition?.nameOrNumber, 'g')
      this.tableRData = tableSourceList.filter(item => {
        if (regex.test(item.projectName) || regex.test(item.projectCode)) {
          return item
        }
      })
    },
    handleDelete(row) {
      // 删除
      this.$ckConfirm({
        content: '确定删除该条记录?',
        title: '提示',
        okFn: (res) => {
          tableSourceList = tableSourceList.filter(item => item.projectId !== row.projectId)
          this.tableRData = this.tableRData.filter(item => item.projectId !== row.projectId)
        },
        cancelFn: (res) => {
          console.log('取消')
        }
      })
    },
    getSelect() {
      sysAccountingUnitPull().then(res => {
        if (res.code === 200) {
          this.dptList = res.data
        } else {
          this.$message.error(res.msg)
        }
      })
      HISDeptCode().then(res => {
        if (res.code === 200) {
          this.kzdptList = res.data
        } else {
          this.$message.error(res.msg)
        }
      })
      // 来源
      listProjectTargetAdministrationPull({
        code: 'sys_unit'
      }).then((res) => {
        if (res.code === 200) {
          this.unitList = res.data
        } else {
          this.$message.error(res.message)
        }
      })
    },
    pageChange(payload) {
      this.currentL = payload.current
      this.pageLSize = payload.pageSize
      this.getHospitalData()
    },
    pageRChange(payload) {
      this.currentR = payload.current
      this.pageRSize = payload.pageSize
    },
    getHospitalData() {
      const params = {
        pageNum: this.currentL,
        pageSize: this.pageLSize,
        nameOrNumber: this.newCondition.nameOrNumber
      }
      this.tableLLoading = true
      listByCodeOrName(params)
        .then(res => {
          this.tableLLoading = false
          if (res.code === 200) {
            this.tableLData = res.data.records
            this.totalL = res.data.total
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(() => {
          this.tableLLoading = false
        })
    },

    handleSystermSearch(value) {
      this.newRCondition = value
      this.getRightTable()
    },
    handleSelection(row) {
      this.leftSelections = row
    },
    // 查询
    handleHospitalSearch(value) {
      this.newCondition = value
      this.getHospitalData()
    },
    handleHospitalReset(val) {
      this.handleHospitalSearch(val)
    }
  }
}
</script>
<style lang="less" scoped>
.newinfo-wraper {
  padding: 10px 10px;
  box-sizing: border-box;
  .top-box {
    display: grid;
    grid-template-columns: 480px 90px 1fr;
    padding: 8px;
    background: #fff;
    border-radius: 2px;
    box-sizing: border-box;
    overflow: hidden;
    height: 63vh;
    .left-box,
    .right-box {
      border: 1px solid #e7ecf8;
      padding: 5px 10px 10px;
      box-sizing: border-box;
      overflow: hidden;
    }
    .middle-box {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .card-box {
    display: flex;
    flex-direction: column;
    .undline {
      height: 30px;
      display: flex;
      align-items: center;
      margin-bottom: 5px;
      font-weight: 700;
      &::before {
        content: "";
        height: 15px;
        border-right: 2px solid #217dfa;
        margin-right: 10px;
      }
    }
    .search-box {
      display: flex;
      margin-bottom: 15px;
    }
    .table-box {
      flex: 1;
      display: flex;
      overflow: hidden;
      flex-direction: column;
    }
  }
}
/deep/.el-checkbox__inner {
  // width: 15px;
  // height: 15px;
  margin-left: 20px;
}
</style>
